import 'package:basic_library/src/utils/easy_loading_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

enum WebViewType {
  url, // url链接
  html, // html代码
}

///
/// 网页加载框架(含进度条)
///
class WebViewFrame extends StatefulWidget {
  final WebViewType webViewType; // 网页类型
  final String url; // url 或 html 代码
  final Widget? bottomWidget; // 底部视图
  final Function? webOnTapCallback;

  const WebViewFrame(
      {Key? key,
      this.webViewType = WebViewType.url,
      required this.url,
      this.bottomWidget,
      this.webOnTapCallback})
      : super(key: key);

  @override
  _WebViewFrameState createState() => _WebViewFrameState();
}

class _WebViewFrameState extends State<WebViewFrame> {
  double _progress = 0;
  InAppWebViewGroupOptions? _options;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();

    _options = InAppWebViewGroupOptions(
        crossPlatform: InAppWebViewOptions(
          useShouldOverrideUrlLoading: true,
          mediaPlaybackRequiresUserGesture: false,
        ),
        android: AndroidInAppWebViewOptions(
          useHybridComposition: true,
        ),
        ios: IOSInAppWebViewOptions(
          allowsInlineMediaPlayback: true,
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _progress < 1.0
            ? LinearProgressIndicator(value: _progress)
            : Container(),
        widget.webViewType == WebViewType.html
            ? Expanded(
                child: SingleChildScrollView(
                  child: Html(
                      data: widget.url,
                      onLinkTap: (String? url, RenderContext rContext,
                          Map<String, String> attributes, element) {
                        if (widget.webOnTapCallback != null) {
                          widget.webOnTapCallback!(url);
                        }
                      }),
                ),
              )
            : Expanded(
                child: InAppWebView(
                  initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
                  initialOptions: _options,
                  onReceivedServerTrustAuthRequest:
                      (controller, challenge) async {
                    // 解决 handshake failed 问题
                    return ServerTrustAuthResponse(
                        action: ServerTrustAuthResponseAction.PROCEED);
                  },
                  onLoadStop: (InAppWebViewController controller, Uri? url) {
                    debugPrint("网页 onLoadStop--》");
                    _isLoading = false;
                    setState(() {});
                  },
                  androidOnPermissionRequest:
                      (controller, origin, resources) async {
                    return PermissionRequestResponse(
                        resources: resources,
                        action: PermissionRequestResponseAction.GRANT);
                  },
                  onProgressChanged: (controller, progress) {
                    _progress = progress / 100;
                    setState(() {});
                  },
                  onLoadError: (controller, url, code, message) {
                    EasyLoadingHelper.showToast(message);
                    _isLoading = false;
                    setState(() {});
                  },
                ),
              ),
        _isLoading
            ? const Center(child: CircularProgressIndicator())
            : Container(),
        widget.bottomWidget ?? Container()
      ],
    );
  }
}
